import { Effect, ImmerReducer, Subscription } from "umi"

import { fetchProductList } from "@/api"
export interface productState {
    productList: Array<any>;
    error: any
}

export interface productModelType {
    namespace: String;
    state: productState;
    effects: {
        fetchProduct: Effect
    };
    reducers: {
        setProduct: ImmerReducer<productState>
    },
    subscriptions: { setup: Subscription }
}

const productModel: productModelType = {
    namespace: "product",
    state: {
        productList: [],
        error: null
    },
    effects: {
        *fetchProduct({ payload }, { call, put, select }) {
            try {
                const res = yield call(fetchProductList)
                yield new Promise((resolve, reject) => {
                    setTimeout(() => {
                        resolve(2000)
                    }, 2000)
                })
                yield put({ type: "setProduct", payload: { data: res.data, error: null } })
            } catch (e) {
                yield put({ type: "setProduct", payload: { data: [], error: e } })
            }
        }
    },
    reducers: {
        setProduct(state, action) {
            state.productList = action.payload.data
            state.error = action.payload.error
        }
    },
    subscriptions: {
        setup(props) {
            // console.log('技术摸鱼摸鱼');
            // console.log(props);
        }
    }
}

export default productModel